package com.zwj.interview.回文结构;

/**
 * @Author: Zwj
 * @Date: 2022/3/1 17:02
 */
public class LongestPalindrome {


    public String longestPalindrome(String s) {
        if (s == null || s.length() < 1){
            return "";
        }
        int start = 0, end = 0;
        for (int i = 0; i < s.length(); i++) {
            //找到长度为奇数的回文串的长度,奇数的话，中心就一个字符
            int len1 = findPalindrome(s, i, i);
            //找到长度为偶数的回文串的长度，偶数的话，中心有两个字符
            int len2 = findPalindrome(s, i, i + 1);
            int len = Math.max(len1, len2);
            if (len > end - start) {
                start = i - (len - 1) / 2;
                end = i + len / 2;
            }
        }
        return s.substring(start, end + 1);
    }


    //以left和right为中心的回文长度,向两边扩散
    public int findPalindrome(String s, int left, int right) {
        while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
            left--;
            right++;
        }
        return right - left - 1;
    }

    public static void main(String[] args) {
        System.out.println(new LongestPalindrome().findPalindrome("babad",0,1));
    }



}